import axios from 'axios'
import notification from 'ant-design-vue/lib/notification'
import modal from 'ant-design-vue/lib/modal'

import storage from 'store'
const ACCESS_TOKEN = ''
import router from '@/router'
// 使用create方法创建axios实例
export const request = axios.create({
  timeout: 10000, // 请求超时时间,
  // headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
  baseURL: ''
})
// 添加请求拦截器
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  if (token) {
    config.headers[ACCESS_TOKEN] = token
  } else {
    delete config.headers[ACCESS_TOKEN]
  }
  return config
})
// 添加响应拦截器
request.interceptors.response.use(response => {
  const data = response.data || {}
  if (data.code === 403) {
    notification.error({
      message: data.code.msg || '缺少权限',
      description: ''
    })
  } else if (data.code === -100) {
    const url = response.config.url
    if (url.indexOf('/admin/info') < 0) {
      /* info 接口的处理在 permission.js里 */
      modal.confirm({
        title: '登录超时，是否立即重新登录?',
        // content: h => <div style="color:red;">Some descriptions</div>,
        okText: '确定',
        cancelText: '取消',
        onOk() {
          router.push('/user/login')
        },
        onCancel() {
        }
      })
    }
  } else if (data.code !== 1) {
    console.error(data)
    modal.error({
      title: '操作出错',
      content: data.msg || '未知错误'
    })
  }
  return data
}, error => {
  let msg = '请求出错'
  let code = 500
  if (error.response) {
    const res = error.response
    code = res.status
    if (res.status === 500) {
      msg = '内部服务错误' + res.data.message
    } else if (res.status === 404) {
      msg = '接口不存在'
      if (res.data.path) {
        msg += (res.data.path || '')
      }
    }
  } else {
    if (error.message) {
      msg = error.message
    }
  }
  modal.error({
    title: '出错了，请联系管理员',
    content: msg
  })
  return Promise.resolve({
    code: code,
    msg: msg
  })
  // return Promise.reject(error)
})
